package com.kcs.fxmargin.service;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.kcs.common.utils.ConnectionUtils;
import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.bo.CheckLimitOrderBO;
import com.kcs.fxmargin.bo.InquiryAccountWSBO;
import com.kcs.fxmargin.dao.CheckLimitOrderDAO;
import com.kcs.fxmargin.ws.InquiryAccountWS;

public class CheckLimitOrderService {
	
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	public CheckLimitOrderBO checkLimit(CheckLimitOrderBO bo)throws Exception{
		Connection connOra = null;
		Connection conn = null;
		CheckLimitOrderDAO dao = null;
		boolean result = false;
		List<CheckLimitOrderBO> accountStatementDataList = null;
		CheckLimitOrderBO dataBo = null;
		InquiryAccountWSBO wsBo = null;
		InquiryAccountWS ws = null;
		Date asOfDate = null;
		
		log.info("Begin : CheckLimitOrderService : checkLimit");
		
		try{
			
			if(validateCheckLimit(bo)){
			
				//-- Get Data from RETAD
				log.info("Get Data from RETAD >>> processing...");
				connOra = ConnectionUtils.getConnection(Constant.ORACLE, Constant.FROM);
				dao = new CheckLimitOrderDAO();
				bo = dao.getTDealsDataFromRETAD(bo, connOra);
				connOra.close();
				log.info("Get Data from RETAD <<< finish");
				
				if(bo.gettDealsList() != null){
					//-- Delete TDeals FX Margin
					log.info("Delete TDeals FX Margin >>> processing...");
					conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO);

					result = dao.deleteTDeals(bo, conn);
					log.info("Delete TDeals FX Margin <<< finish");
					
					//-- Insert TDeals FX Margin
					log.info("Insert TDeals FX Margin >>> processing...");
					dao.insertTDeals(bo, conn);
					log.info("Insert TDeals FX Margin <<< finish");
					
					//-- Get t_pre_order
					log.info("Get t_pre_order >>> processing...");
					bo = dao.getPreOrderAmount(bo, conn);
					log.info("Get t_pre_order <<< finish : "+bo.getPreOrderAmount());
					
					//-- Get m_cust_info
					log.info("Get m_cust_info >>> processing...");
					bo = dao.getMCustInfo(bo, conn);
					log.info("Get t_pre_order <<< finish : "+bo.getmCustInfo());

					if(bo.getmCustInfo() != null){
						bo.setCustLimitAvailable(bo.getmCustInfo().getCustLimitAmt().toString());
					}
					log.info("Cust Limit Available : "+bo.getCustLimitAvailable());
					
					//Get as_of_date
					log.info("Get as_of_date >>> processing...");
					asOfDate = commonUtils.convertUtilDatetoSQLDate(commonUtils.getCurrentDate());
					bo.setAsOfDate(asOfDate);
					log.info("Get as_of_date <<< finish : "+bo.getAsOfDate());
					
					//-- Call WS InquiryAccountDetail
					log.info("Call WS InquiryAccountDetail >>> processing...");
					ws = new InquiryAccountWS();
					wsBo = new InquiryAccountWSBO();
					wsBo.setUser(bo.getCreateUser());
					wsBo.setCifNo(bo.getInCifNo());
					wsBo.setMarginAccNo(bo.getmCustInfo().getMarginAccNo());
					wsBo = ws.inquiryAccountDetail(wsBo);
					bo.setOutsBal(wsBo.getOutsBal()==null?new BigDecimal(0):wsBo.getOutsBal());
					log.info("Call WS InquiryAccountDetail <<< finish : "+bo.getOutsBal());
					
					
					//-- Check t_acc_pos
					log.info("Check t_acc_pos >>> processing...");
					bo = dao.getTAccPos(bo, conn);
					log.info("Check t_acc_pos <<< finish : "+bo.gettAccPos());
					if(bo.gettAccPos() != null){
						dao.updateTAccPos(bo,conn);
						log.info("Update TAccPos success!");
					}else{
						dao.insertTAccPos(bo,conn);
						log.info("Insert TAccPos success!");
					}
					
					//-- Call WS InquiryAccountStatement
					log.info("Call WS InquiryAccountStatement >>> processing...");
					wsBo = ws.inquiryAccountStatement(wsBo);
					bo.setAccountStatementDataList(wsBo.getAccountStatementDataList()); 
					accountStatementDataList = bo.getAccountStatementDataList();
					
					log.info(">"+accountStatementDataList +" size = "+((accountStatementDataList!=null)?accountStatementDataList.size():"-1"));
					if(accountStatementDataList != null){
						
						for(int i=0; i<accountStatementDataList.size(); i++){
							dataBo = accountStatementDataList.get(i);
							dataBo.setmCustInfo(bo.getmCustInfo());
							dataBo.settAccPos(bo.gettAccPos());
							log.info("["+i+"] : "+dataBo.getTransRefNo());
							
							//-- Check t_acc_tran
							dataBo = dao.getTAccTrans(dataBo, conn);
							log.info("Check TAccTrans : "+dataBo.gettAccTran());
							if(dataBo.gettAccTran() == null){
								result = dao.insertTAccTran(dataBo, conn);
								log.info("Insert TAccTran : "+result);
							}
						}
					}
					log.info("Call WS InquiryAccountStatement <<< finish");
					
					//-- Call SPCalMarginLimit
					log.info("Call SPCalMarginLimit >>> processing...");
					bo = dao.callMarginLimit(bo, conn);
					bo.setFxLimitAvailable(bo.getMarginLimit());
					log.info("Call SPCalMarginLimit <<< finish : "+bo.getFxLimitAvailable());
					
					log.info("Get Initial Margin >>> processing...");
					bo = dao.getInitialMargin(bo, conn);
					log.info("Get Initial Margin <<< finish : "+bo.getInitialMargin());
					
				}
				
				conn.commit();
				result =  true;
				
				
			}else{
				throw new Exception(Constant.ERR_CIF_NO_EMPTY);
			}
			
			bo.setProcessSuccess(result);
			
		}catch(Exception e){
			if(conn != null){
				try{
					conn.rollback();
				}catch(Exception ex){
					throw ex;
				}
			}
				
			throw e;
		}finally{
			if(connOra != null){
				try{
					connOra.close();
				}catch(Exception ex){
					throw ex;
				}
			}
			if(conn != null){
				try{
					conn.close();
				}catch(Exception ex){
					throw ex;
				}
			}
		}
		
		log.info("End : CheckLimitOrderService : checkLimit");
		return bo;
		
	}
	
	private boolean validateCheckLimit(CheckLimitOrderBO bo){
		return !bo.getInCifNo().equals("");
	}

}
